const express = require('express')
const app = express()
const fs = require('fs');
// const cmd=require('node-cmd');
const execSync = require('child_process').execSync;

app.get('/update/:app', function(req, res) {
    // res.send('Hello World!')

    var output = '';

    var app = req.params.app;

    if (!fs.existsSync('/var/www/py-site/' + app)) {
        res.send('APP DOESN\'T EXIST');
    }
    var python = null;
    var pip = null;
    var data = fs.readFileSync('/var/www/py-site/'+app+'/deploy/uwsgi.ini', 'utf-8');

    var reg_env = /virtualenv = (.*)/;
    // var reg_env = /virtualenv = (.*)/;
    var env = data.match(reg_env)[1];
    python = env + '/bin/python';
    pip = env + '/bin/pip';
    // var env = data.match(reg_env)[1];

    console.log(python);

    output += execSync('cd /var/www/py-site/'+app+' && git pull && '+pip+' install -r requirements.txt && '+python+' manage.py collectstatic --noinput && '+python+' manage.py migrate && touch /etc/uwsgi/apps-enabled/'+app+'.ini');

    res.send('<pre>'+output+'</pre>');
})

app.listen(3000, function() {
    console.log('Example app listening on port 3000!')
})
